package plugin

import (
	"fmt"
	"os"
	"strconv"
	"strings"
)

type UserInfo struct {
	IpPort string
	User string
	Passwd string
}
var UserInfoMap map[int]UserInfo
var cmds []string

//用于判断配置文件每行首位的ip信息是否为数字
func IsNum(s string) bool {
	_, err := strconv.ParseFloat(s, 64)
	return err == nil
}

//判断ip是否为范围格式
func HasRange(s string) bool{
	b := strings.Split(s,"..")
	if len(b) > 1{
		return true
	}else{
		return false
	}
}

//截取范围的ip值
func DelIPLast(a string) int {
	var s string = ""
	for i :=0 ; i < len(a) - 1 ; i++ {
		s += string(a[i])
	}
	i ,err := strconv.Atoi(s)
	if err != nil {
		fmt.Printf("string -> int err: %s\n",err)
	}
	return i
}
//获取默认端口
func GetPort(pwd string)  string{
	var port string
	fileobj ,err := os.ReadFile(pwd)
	if err != nil {
		fmt.Printf("Read file failed , err is %v",err)
	}
	IPInfo := strings.Split(string(fileobj),"\r")
	for _,value := range IPInfo {
		userpw := strings.Fields(value)
		if len(userpw) >= 1 && userpw[0][:1] == "P"{
			if userpw[0][:4] == "PORT"{
				a := strings.Split(userpw[0],"=")
				port = ":" + strings.TrimSpace(a[1])
			}
		}
	}
	return port
}


func GetUserMap(pwd string) (map[int]UserInfo,[]string){
	port := GetPort(pwd)
	fileobj ,err := os.ReadFile(pwd)
	if err != nil {
		fmt.Printf("Read file failed , err is %v",err)
	}
	usermap := make(map[int]UserInfo,30)
	cmds = make([]string,0,10)
	//用于配置文件中未指定user和passwd的ip使用
	var (
		user string
		passwd string
	)

	IPInfo := strings.Split(string(fileobj),"\r")
	//轮询配置文件中每行的内容进行判断
	var num = 0
	for i := 0 ; i< len(IPInfo); i++ {
		userpw := strings.Fields(IPInfo[i])

		//若用户未指定user和passwd 使用上一位ip指定的user和passwd
		user = usermap[i-1].User
		passwd = usermap[i-1].Passwd

		//判断配置文件中的ip是否为范围格式
		if len(userpw) >= 1 &&  IsNum(string(userpw[0][0]))== true &&  userpw[0][0] != '#' && HasRange(userpw[0])== true  {
			//fmt.Println(userpw)
			ran := strings.Split(userpw[0],".")
			//ip的前三位
			IPZeroToThree := strings.Join(ran[0:3],".")

			var (
				min int
				max int
			)
			for k ,v := range ran{
				if k == 3 {
					min ,err = strconv.Atoi(v[1:])
					if err != nil{
						fmt.Printf("string -> int err: %s\n",err)
					}
				}
				if k == 5 {
					vs := strings.Split(v,":")
					max = DelIPLast(vs[0])
				}
			}
			//fmt.Println("range",min,"->",max)
			//获取配置文件中的范围ip并存入map
			for j := min; j <= max; j++ {
				IPfour := strconv.Itoa(j)
				IP :=  IPZeroToThree + "." + IPfour

				if len(strings.Split(userpw[0],":")) > 1{
					port = ":" + strings.Split(userpw[0],":")[1]
				}
				IP = IP + port
				if len(userpw) == 3 {
					UsIn := UserInfo{
						IpPort: IP,
						User: userpw[1],
						Passwd: userpw[2],
					}
					usermap[i+num] = UsIn
				} else {
					UsIn := UserInfo{
						IpPort: IP,
						User: user,
						Passwd: passwd,
					}
					usermap[i+num] = UsIn
				}
				num += 1
			}

			//判断是否指定了ip的用户和密码，若未指定 使用上一位ip指定的user和passwd
		}else if len(userpw) > 2 && userpw[0][0] != '#' && IsNum(string(userpw[0][0])) == true{
			//fmt.Println(userpw[0],userpw[1],userpw[2])
			//判断ip后面是否定义了端口，如果否，使用默认配置文件设置的默认端口
			ipPort := strings.Split(userpw[0],":")
			if len(ipPort)< 2{
				userpw[0] = ipPort[0] + port
			}
			UsIn := UserInfo{
				IpPort: userpw[0],
				User: userpw[1],
				Passwd: userpw[2],
			}
			usermap[i] = UsIn

		}else if len(userpw) == 1 && userpw[0][0] != '#' && IsNum(string(userpw[0][0])) == true{
			ipPort := strings.Split(userpw[0],":")
			if len(ipPort)< 2{
				userpw[0] = ipPort[0] + port
			}
			////若用户未指定user和passwd 使用上一位ip指定的user和passwd
			//user = usermap[i-1].User
			//passwd = usermap[i-1].Passwd

			UsIn := UserInfo{
				IpPort: userpw[0],
				User: user,
				Passwd: passwd,
			}
			usermap[i] = UsIn
		}

		//var cmd int
		//遍历配置文件中的命令

		if  len(userpw) >= 1 && userpw[0][0] != '#' && IsNum(string(userpw[0][0])) == false && userpw[0][0] != '['{
			cmd := strings.Join(userpw," ")
			cmds = append(cmds, cmd)
		}
	}
	cmds = cmds[1:]

	return usermap,cmds
}

